<?php
/**
 * Cust Return Head
 */
class CRH extends AppModel {
    var $name = 'CRH';

    var $useTable = 'cust_return_heads';

    var $displayField = 'return_no';

    var $hasMany = array(
            'CR' => array(
                            'foreignKey' => 'cust_return_head_id',
            )
    );

    var $belongsTo = array(
            'Customer' => array(
                            'fields' => array('id', 'cust_no', 'name')
            ),
            'Site' => array(
                            'fields' => array('id', 'site_no', 'name')
            ),
            'CRS' => array(
                            'foreignKey' => 'cust_return_status_id',
            ),
            'User' => array(
                            'foreignKey' => 'collector_id',
                            'fields' => array('username', 'name')
            )
    );

    var $validate = array(
            'return_no' => array(
                            'notEmpty' => array(
                                            'rule' => array('notEmpty'),
                                            'message' => 'Return no. is required.',
                                            'required' => true,
                            ),
                            'isUnique' => array(
                                            'rule' => 'isUnique',
                                            'message' => 'This Stock in no is already taken.',
                                            'on' => 'create'
                            ),
            ),
            'return_date' => array(
                            'rule' => array('date', 'dmy'),
                            'message' => 'Return date is required.',
                            'required' => true,
            ),
            'customer_id' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Customer is required.',
                            'required' => true,
            ),
            'site_id' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Site is required.',
                            'required' => true,
            ),
    );

    function beforeSave() {
        if (isset($this->data['CRH']['return_date'])) {
            $this->data['CRH']['return_date'] = $this->dateFormatBeforeSave($this->data['CRH']['return_date']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$custStockOutReturnHead) {
            if (isset($custStockOutReturnHead['CRH'])) {
                if (isset($custStockOutReturnHead['CRH']['return_date'])) {
                    $custStockOutReturnHead['CRH']['return_date'] = $this->dateFormatAfterFind($custStockOutReturnHead['CRH']['return_date']);
                }
            }
        }
        return $results;
    }

    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int $id cust_stock_in_head_id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'CRS',
                'CR' => array('Product' => array('part_no', 'text', 'Unit'), 'CustProductSite')
                )
        );
        $data = $this->findById($id);

        $this->CR->bindModel(array(
                'hasMany' => array(
                        'ProductSerial' => array(
                                'foreignKey' => 'cust_stock_in_id',
                                'conditions' => array(
                                        'cust_stock_out_type' => CR::CUST_STOCK_OUT_TYPE
                                )
                        )
                )
                )
        );

        $Product = $this->CR->Product;
        $PS = $this->CR->ProductSerial;
        $CL = $PS->CustLocation;

        // วนลูปรายการ CR
        foreach($data['CR'] as &$cr) {
            // หา Location ที่มีอยู่ใน CR รายการนี้
            $psCLs = $PS->find('all', array(
                    'fields' => array('DISTINCT cust_location_id'),
                    'conditions' => array(
                            'cust_stock_out_id' => $cr['id'],
                            'cust_stock_out_type' => CR::CUST_STOCK_OUT_TYPE,
                            'product_id' => $cr['product_id']
                    )
                    )
            );

            // แปะ Location ที่ได้เข้า CR
            foreach ($psCLs as $psCl) {
                $CL->contain();
                $custLocation = $CL->findById($psCl['ProductSerial']['cust_location_id']);

                // option สำหรับ query product serial
                $options = array(
                        'contain' => array(),
                        'conditions' => array(
                                'cust_stock_out_id' => $cr['id'],
                                'cust_stock_out_type' => CR::CUST_STOCK_OUT_TYPE,
                                'product_id' => $cr['product_id'],
                                'cust_location_id' => $psCl['ProductSerial']['cust_location_id']
                        )
                );

                // นับจำนวนที่ stock out ใน location นี้
                $ps_count = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

                $custLocation['return_qty'] = $ps_count;
                $custLocation['PS'] = $ps;

                $cr['ProductLocation'][] = $custLocation;
            }
        }
        return $data;
    }
}
?>
